import 'package:bruno/bruno.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/scheduler/ticker.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:xiongmao_clean_flutter_module/business/common/contract/bean/contract_main_info_entity.dart';
import 'package:xiongmao_clean_flutter_module/business/common/contract/page/contract_pay_page.dart';
import 'package:xiongmao_clean_flutter_module/business/common/contract/page/contract_template_page.dart';
import 'package:xiongmao_clean_flutter_module/business/common/web/page/web_page.dart';
import 'package:xiongmao_clean_flutter_module/res/colors.dart';
import 'package:xiongmao_clean_flutter_module/res/gaps.dart';
import 'package:xiongmao_clean_flutter_module/util/common_utils.dart';
import 'package:xiongmao_clean_flutter_module/widgets/load_image.dart';

import '../../../../mvp/base_page.dart';
import '../../../../mvp/power_presenter.dart';
import '../../../../util/log_utils.dart';
import '../../../../util/permission_util.dart';
import '../../../../widgets/custom_border_text_view.dart';
import '../../../../widgets/select_tab/select_tab_widget.dart';
import '../../../../widgets/wrap_content_height_sliver_header.dart';
import '../../base/base_web_page.dart';
import '../controller/contract_main_info_controller.dart';
import '../iview/contract_main_info_iview.dart';
import '../persenter/contract_main_persenter.dart';
import 'contract_edit_seal_page.dart';
import 'contract_history_page.dart';

/**
 * 电子合同
 */
class ContractPage extends StatefulWidget {
  @override
  _ContractPageState createState() => _ContractPageState();
}

class _ContractPageState extends State<ContractPage> with BasePageMixin<ContractPage, PowerPresenter<dynamic>>
,SingleTickerProviderStateMixin implements ContractMainInfoIView {
  ContractMainInfoPresenter? _presenter;
  final ContractMainInfoController _controller = Get.put(ContractMainInfoController());
  final _outerRefreshIndicatorKey = GlobalKey<RefreshIndicatorState>();
  final _scrollViewController = ScrollController();

  late TabController _tabController;
  List tabs  = ["入职合同模版","离职合同模版"];
  final _pageController = PageController();

  late ContractTemplatePage entryPage;
  late ContractTemplatePage dimissionPage;

  void initState() {
    super.initState();
    VoidCallback addListener = BoostChannel.instance.addEventListener("ContractFddAuth", (key, arguments) async {
      LogUtil.e("object----getContractMainInfo-----");
      _presenter?.getContractMainInfo();
    });

    _tabController = TabController(vsync: this, length: tabs.length);
    _tabController.addListener(() {
      _handleTabSelection();
    });
    //获取合同类型
    _presenter?.getContractMainInfo();
    entryPage = ContractTemplatePage(TYPE_ENTRY);
    dimissionPage = ContractTemplatePage(TYPE_SEPARATION);
  }

  void _handleTabSelection() {
    FocusScope.of(context).requestFocus(FocusNode());
    if (_tabController.indexIsChanging) {
      // 当前选中的选项卡发生变化
      MyLog.e('Selected tab: ${_tabController.index}');
      _pageController.jumpToPage(_tabController.index);
      _controller.updateCurrentTabIndex(_tabController.index);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      backgroundColor: Colours.base_primary_bg_page,
      appBar: BrnAppBar(
          title: '电子合同',
          backLeadCallback: () {
            BoostNavigator.instance.pop();
          }),
      body: SafeArea(child: Column(
            children: [
              Expanded(child: Container(height:500,child: RefreshIndicator(
                key: _outerRefreshIndicatorKey,
                onRefresh: () async {
                  // notifyData();
                },
                child: NestedScrollView(
                  controller: _scrollViewController,
                  headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
                    return [
                      WrapContentHeightSliverHeader(child: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              //顶部信息
                              Container(
                                padding: EdgeInsets.only(left: 16, right: 10, top: 10, bottom: 10),
                                color: Colors.white,
                                child: Row(
                                  children: [
                                    //左边的内容
                                    Expanded(
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Row(
                                              children: [
                                                Text(_controller.infoEntity.value.contractCount??"0",
                                                  style: TextStyle(color: Colours.base_primary, fontWeight: FontWeight.bold, fontSize: 21),
                                                ),
                                                Text(
                                                  " 份",
                                                  style: TextStyle(color: Colours.base_primary_text_body, fontSize: 14),
                                                ),
                                              ],
                                            ),
                                            Text(
                                              "电子合同剩余可用份数",
                                              style: TextStyle(color: Colours.base_primary_text_body, fontSize: 14),
                                            )
                                          ],
                                        )),
                                    //右边的内容
                                    Row(
                                      // mainAxisAlignment: MainAxisAlignment.end,
                                      children: [
                                        BrnSmallOutlineButton(
                                          title: "历史记录",
                                          fontSize: 14,
                                          themeData:BrnButtonConfig(bigButtonHeight:27),
                                          textColor: Colours.base_primary,
                                          lineColor: Colours.base_primary,
                                          onTap: () {
                                            BoostNavigator.instance.push("contractHistoryPage");
                                          },
                                        ),
                                        Gaps.hGap8,
                                        BrnSmallMainButton(
                                          title: '购买',
                                          fontSize: 14,
                                          width: 60,
                                          textColor: Colours.white,
                                          bgColor: Colours.base_primary,
                                          onTap: () {
                                            // BoostChannel.instance.sendEventToNative("native_CommonEvent", {"method": "pay_native"});
                                            BoostNavigator.instance.push("contractPayPage").then((value) => _presenter?.getContractMainInfo());
                                          },
                                        )
                                      ],
                                    ),
                                  ],
                                ),
                              ),
                              //合同签署方式介绍
                              Container(
                                color: Colors.white,
                                margin: const EdgeInsets.only(top: 10),
                                padding: const EdgeInsets.all(16.0),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      children: [
                                        Expanded(
                                          child: Text(
                                            "合同签署方式",
                                            style: TextStyle(fontSize:15, fontWeight: FontWeight.bold,color: Colours.base_primary_text_title),
                                          ),
                                        ),
                                        Text(
                                          "实名认证签署",
                                          style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold,color: Colours.base_primary_text_title),
                                        ),
                                      ],
                                    ),
                                    Gaps.vGap8,
                                    Text(
                                      "1.该方式的电子合同，符合国家《民法典》对电子合同的要求，具有完整的法律效力。\n2.签署过程需要签署方实名信息认证，对接国家认证权威机构颁发的CA证书，作签署信息存案。\n3.每发起一次签署，消耗一次合同份数。",
                                      style: TextStyle(color: Colours.base_primary_text_body, fontSize: 14),
                                    ),
                                  ],
                                ),
                              ),
                              //合同印章
                              Container(
                                color: Colors.white,
                                margin: const EdgeInsets.only(top: 10),
                                padding: const EdgeInsets.all(16.0),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      "合同印章",
                                      style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold,color: Colours.base_primary_text_title),
                                    ),
                                    Gaps.vGap13,
                                    Row(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        LoadImage(
                                          _controller.infoEntity.value.sealCdnUrl ?? "",
                                          width: 89,
                                          height: 89,
                                        ),
                                        Gaps.hGap22,
                                        ///已认证的情况
                                        Visibility(
                                            visible: (_controller.infoEntity.value.customerStatus == "1"),
                                            child: Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                Text("${_controller.infoEntity.value.cert?.companyName}",
                                                  style: TextStyle(fontWeight: FontWeight.bold,color: Colours.base_primary_text_title,fontSize: 15),
                                                ),
                                                Gaps.vGap2,
                                                Text(
                                                  "企业印章已实名认证",
                                                  style: TextStyle(color: Colours.base_primary, fontSize: 12),
                                                ),
                                                Gaps.vGap8,
                                                Row(
                                                  children: [
                                                    CustomBorderText(
                                                      text: '重新认证',
                                                      fontSize: 12,
                                                      borderRadius: 2,
                                                      onTapCallback: () {
                                                        // 处理点击事件逻辑
                                                        getContractRegisterUser(true);
                                                      },
                                                    ),
                                                    Gaps.hGap4,
                                                    CustomBorderText(
                                                      text: '编辑印章',
                                                      fontSize: 12,
                                                      borderRadius: 2,
                                                      onTapCallback: () {
                                                        var cert = _controller.infoEntity.value.cert;
                                                        BoostNavigator.instance.push("contractEditSealPage", arguments: {
                                                          "companyName":cert?.companyName??"",
                                                          "organization":cert?.organization??"",
                                                          "sealCdnUrl":_controller.infoEntity.value.sealCdnUrl,
                                                          "customer_id":_controller.infoEntity.value.customerId
                                                        }).then((value){
                                                          _presenter?.getContractMainInfo();
                                                        });
                                                      },
                                                    )
                                                  ],
                                                ),
                                              ],
                                            )),
                                        ///未认证的情况
                                        Visibility(
                                            visible: (_controller.infoEntity.value.customerStatus == "3"||_controller.infoEntity.value.customerStatus=="2"),
                                            child: Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                Text(
                                                  "合同印章(企业/法人信息)\n${(_controller.infoEntity.value.customerStatus == "3")?"认证中":"未认证"}",
                                                  style: TextStyle(fontWeight: FontWeight.bold, color: Colors.red),
                                                ),
                                                Gaps.vGap10,
                                                Row(children: [
                                                  Container(
                                                    margin: EdgeInsets.only(right: 10),
                                                    color: Colors.red,
                                                    padding: EdgeInsets.only(
                                                      left: 10,
                                                      right: 10,
                                                    ),
                                                    child: InkWell(
                                                      child: Text(
                                                        "去认证",
                                                        style: TextStyle(color: Colors.white, fontSize: 14),
                                                      ),
                                                      onTap: () {
                                                        getContractRegisterUser(false);},
                                                    ),
                                                  ),
                                                  Visibility(child: Container(
                                                    color: Colors.red,
                                                    padding: EdgeInsets.only(
                                                      left: 10,
                                                      right: 10,
                                                    ),
                                                    child: InkWell(
                                                      child: Text(
                                                        "重新认证",
                                                        style: TextStyle(color: Colors.white, fontSize: 14),
                                                      ),
                                                      onTap: () {
                                                        getContractRegisterUser(true);
                                                      },
                                                    ),
                                                  ),visible: _controller.infoEntity.value.customerStatus == "3",),
                                                ],)
                                              ],
                                            ))
                                      ],
                                    ),
                                    Gaps.vGap10,
                                    Visibility(
                                        visible: _controller.infoEntity.value.customerStatus == "1",
                                        child: Column(children: [
                                          Gaps.line,
                                          Gaps.vGap16,
                                          Row(
                                            crossAxisAlignment: CrossAxisAlignment.start, // 设置顶部对齐
                                            children: [
                                              Expanded(
                                                  child: Column(
                                                    crossAxisAlignment: CrossAxisAlignment.start,
                                                    children: [
                                                      Text(
                                                        "公司印章自动签署",
                                                        style: TextStyle(
                                                          fontWeight: FontWeight.bold,
                                                          fontSize: 14,
                                                          color: Colours.base_primary_text_title,
                                                        ),
                                                      ),
                                                      Text(
                                                        "开启后，项目现场人员办理入离职时才可发起电子合同签署",
                                                        style: TextStyle(fontSize: 12, color: Colours.base_primary_text_body),
                                                      ),
                                                    ],
                                                  )),
                                              Opacity(opacity: (_controller.infoEntity.value.sealAutoSignStatus == "1") ? 0.3 : 1.0,child: BrnSwitchButton(
                                                size: const Size(40, 20),
                                                value: (_controller.infoEntity.value.sealAutoSignStatus == "1") ? true : false,
                                                // 使用新变量来表示Switch的状态
                                                onChanged: (bool value) {
                                                  if (value) {
                                                    BrnDialogManager.showConfirmDialog(context, title: "提示", message: '开启自动签署后，发起合同签约时，无需公司法人短信确认即可自动完成公司印章签署，是否确认开启？', cancel: '取消', confirm: '开启授权', onConfirm: () {
                                                      Get.back();
                                                      //请求自动签署的接口 如果是关闭的情况，才能请求接口哦
                                                      _presenter?.getAutoSignUrl(_controller.infoEntity.value.customerId);
                                                    }, onCancel: () {
                                                      Get.back();
                                                    });
                                                  }else{
                                                    BrnDialogManager.showSingleButtonDialog(context, label: "我已知晓",title: "提示",message: "本功能暂不支持关闭，若您想停用电子合同，请在下方的应用场景中取消勾选所有场景即可。",onTap: (){
                                                      Get.back();
                                                    });
                                                  }
                                                },
                                              ),),
                                            ],
                                          )
                                        ],)),
                                  ],
                                ),
                              ),
                              // 入职、离职的配置
                              Visibility(child: Container(
                                padding: const EdgeInsets.only(left: 16.0, right: 16.0, bottom: 16.0),
                                color: Colors.white,
                                child: Row(
                                  children: [
                                    Expanded(
                                        child: Text(
                                          "应用场景",
                                          style: TextStyle(
                                            fontSize: 14,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        )),
                                    Container(
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(30.0),
                                        border: Border.all(color: (_controller.infoEntity.value.signSetting?.labelEnabledStatus?.entryContract ?? false) ? Colours.base_primary: Colours.base_primary_line_b),
                                        color: (_controller.infoEntity.value.signSetting?.labelEnabledStatus?.entryContract ?? false) ? Colours.base_primary_green_trans: Colours.white,
                                      ),
                                      padding: EdgeInsets.only(left: 20.0, right: 20, top: 4, bottom: 4),
                                      child: InkWell(
                                        child: Center(
                                          child: Text(
                                            "入职",
                                            style: TextStyle(
                                              color:  (_controller.infoEntity.value.signSetting?.labelEnabledStatus?.entryContract ?? false) ? Colours.base_primary: Colours.base_primary_text_body,
                                              fontSize: 14,
                                            ),
                                          ),
                                        ),
                                        onTap: () {
                                          _presenter?.getUpdateContractStatus('{"EntryContract":${!(_controller.infoEntity.value.signSetting?.labelEnabledStatus!.entryContract ?? false)}}');
                                        },
                                      ),
                                    ),
                                    Gaps.hGap10,
                                    Container(
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(30.0),
                                        border: Border.all(color: (_controller.infoEntity.value.signSetting?.labelEnabledStatus?.separationContract ?? false) ? Colours.base_primary : Colours.base_primary_line_b),
                                        color: (_controller.infoEntity.value.signSetting?.labelEnabledStatus?.separationContract ?? false) ? Colours.base_primary_green_trans : Colours.white,
                                      ),
                                      padding: EdgeInsets.only(left: 20.0, right: 20, top: 4, bottom: 4),
                                      child: InkWell(
                                        child: Center(
                                          child: Text(
                                            "离职",
                                            style: TextStyle(
                                              color: (_controller.infoEntity.value.signSetting?.labelEnabledStatus?.separationContract ?? false) ? Colours.base_primary : Colours.base_primary_text_body,
                                              fontSize: 14,
                                            ),
                                          ),
                                        ),
                                        onTap: () {
                                          _presenter?.getUpdateContractStatus('{"SeparationContract":${!(_controller.infoEntity.value.signSetting?.labelEnabledStatus?.separationContract ?? false)}}');
                                        },
                                      ),
                                    ),
                                  ],
                                ),
                              ),visible: (_controller.infoEntity.value.sealAutoSignStatus == "1"),),
                              Gaps.vBlock12,
                            ],
                          )),
                      WrapContentHeightSliverHeader(
                          pinned: true,
                          child: Visibility(child: Container(
                            color: Colours.white,
                            width: double.maxFinite,
                            child: TabBar(
                              //下面isScrollable和padding是为了tab居左对齐 去掉则为居中
                              // isScrollable: true,
                              // padding: EdgeInsets.only(left: 0),
                              controller: _tabController,
                              labelColor: Colours.base_primary_text_title,
                              unselectedLabelColor:
                              Colours.base_primary_text_caption,
                              labelStyle: TextStyle(
                                  fontSize: 15, fontWeight: FontWeight.bold),
                              unselectedLabelStyle: TextStyle(
                                  fontSize: 15, fontWeight: FontWeight.bold),
                              indicatorColor: Colours.base_primary,
                              indicatorSize: TabBarIndicatorSize.label,
                              // indicatorPadding:
                              // const EdgeInsets.only(left: 15, right: 15),
                              tabs: tabs.map((e) => Tab(text: e)).toList(),
                            ),
                          ),visible: (_controller.infoEntity.value.sealAutoSignStatus == "1"))),
                    ];
                  },
                  body: Column(
                    children: [
                      Visibility(child: Expanded(
                        child: PageView(
                          controller: _pageController,
                          children: [entryPage,dimissionPage],
                          onPageChanged: (index) {
                            _tabController.animateTo(index);
                            _controller.updateCurrentTabIndex(_tabController.index);
                            // print(_scrollViewController.offset);
                            // if (index == 1) {
                            //   if (_scrollViewController.offset > 600) {
                            //     _scrollViewController
                            //         .jumpTo(_scrollViewController.offset - 70);
                            //   }
                            // }
                          },
                        ),
                      ),visible: (_controller.infoEntity.value.sealAutoSignStatus == "1"))
                    ],
                  ),
                ),),)),
            ],
          )),
    );
  }

  @override
  PowerPresenter createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(this);
    _presenter = ContractMainInfoPresenter(_controller);
    powerPresenter.requestPresenter([_presenter!]);
    return powerPresenter;
  }

  @override
  void getContractMainInfo(ContractMainInfoEntity data) {
    _controller.updateContractMainInfoEntity(data);
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
  }
  
  void getContractRegisterUser(bool enforce) {
    if(enforce){
      BrnDialogManager.showConfirmDialog(context, title: "提示", message: '以前的认证信息都将清除，是否确认执行？', cancel: '取消', confirm: '确定', onConfirm: () {
        Get.back();
        _presenter?.getContractRegisterUser(enforce);
      }, onCancel: () {
        Get.back();
      });
    }else{
      _presenter?.getContractRegisterUser(enforce);
    }
  }
}
